import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../widgets/excel/excel_upload_widget.dart';
import '../../widgets/excel/excel_parse_result_widget.dart';
import '../../widgets/platform/adaptive_card.dart';
import '../../../data/models/project_model.dart';

/// Excel处理页面
/// 支持Excel文件上传、解析和结果展示
class ExcelPage extends ConsumerStatefulWidget {
  final ProjectModel? selectedProject;

  const ExcelPage({
    super.key,
    this.selectedProject,
  });

  @override
  ConsumerState<ExcelPage> createState() => _ExcelPageState();
}

class _ExcelPageState extends ConsumerState<ExcelPage> {
  ProjectModel? _currentProject;
  String? _currentExcelPlanId;
  bool _showParseResult = false;
  List<ExcelPlanModel> _excelPlans = [];
  bool _isLoadingPlans = false;

  @override
  void initState() {
    super.initState();
    _currentProject = widget.selectedProject;
    if (_currentProject != null) {
      _loadExcelPlans();
    }
  }

  /// 加载Excel计划列表
  Future<void> _loadExcelPlans() async {
    if (_currentProject == null) return;

    setState(() {
      _isLoadingPlans = true;
    });

    try {
      // 调用实际API获取Excel计划列表
      await Future.delayed(const Duration(seconds: 1));
      setState(() {
        _excelPlans = ExcelPlanModel.mockList();
        _isLoadingPlans = false;
      });
    } catch (e) {
      setState(() {
        _isLoadingPlans = false;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: SelectableText('加载Excel计划列表失败: ${e.toString()}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  /// 处理上传成功
  void _onUploadSuccess() {
    setState(() {
      _showParseResult = false;
    });
    _loadExcelPlans();
  }

  /// 处理上传错误
  void _onUploadError(String error) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: SelectableText(error),
        backgroundColor: Colors.red,
      ),
    );
  }

  /// 查看解析结果
  void _viewParseResult(String excelPlanId) {
    setState(() {
      _currentExcelPlanId = excelPlanId;
      _showParseResult = true;
    });
  }

  /// 生成任务
  void _onGenerateTasks(Map<String, dynamic> parseResult) {
    // 实现任务生成逻辑
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('任务生成'),
        content: SelectableText(
            '成功生成${parseResult['requirements']?.length ?? 0}个任务'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('确定'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const SelectableText('Excel处理'),
        backgroundColor: Colors.blue.shade50,
        foregroundColor: Colors.blue.shade700,
        elevation: 0,
        actions: [
          if (_currentProject != null)
            PopupMenuButton<String>(
              onSelected: (value) {
                switch (value) {
                  case 'refresh':
                    _loadExcelPlans();
                    break;
                  case 'switch_project':
                    _showProjectSelector();
                    break;
                }
              },
              itemBuilder: (context) => [
                const PopupMenuItem(
                  value: 'refresh',
                  child: Row(
                    children: [
                      Icon(Icons.refresh),
                      SizedBox(width: 8),
                      SelectableText('刷新'),
                    ],
                  ),
                ),
                const PopupMenuItem(
                  value: 'switch_project',
                  child: Row(
                    children: [
                      Icon(Icons.swap_horiz),
                      SizedBox(width: 8),
                      SelectableText('切换项目'),
                    ],
                  ),
                ),
              ],
            ),
        ],
      ),
      body: _currentProject == null
          ? _buildProjectSelector()
          : Column(
              children: [
                // 项目信息栏
                _buildProjectInfoBar(),

                Expanded(
                  child: _showParseResult && _currentExcelPlanId != null
                      ? _buildParseResultView()
                      : _buildMainContent(),
                ),
              ],
            ),
    );
  }

  /// 其余方法实现
  Widget _buildProjectSelector() {
    return Center(
      child: AdaptiveCard(
        margin: const EdgeInsets.all(32),
        child: Padding(
          padding: const EdgeInsets.all(32),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Icon(
                Icons.folder_open,
                size: 64,
                color: Colors.grey,
              ),
              const SizedBox(height: 16),
              const SelectableText(
                '请选择一个项目',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w500,
                ),
              ),
              const SizedBox(height: 8),
              SelectableText(
                '您需要先选择一个项目才能上传Excel文件',
                style: TextStyle(
                  color: Colors.grey.shade600,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 24),
              ElevatedButton(
                onPressed: _showProjectSelector,
                child: const SelectableText('选择项目'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildProjectInfoBar() {
    if (_currentProject == null) return const SizedBox.shrink();

    return Container(
      padding: const EdgeInsets.all(16),
      color: Colors.blue.shade50,
      child: Row(
        children: [
          const Icon(Icons.folder, color: Colors.blue),
          const SizedBox(width: 8),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SelectableText(
                  _currentProject!.projectName,
                  style: const TextStyle(
                    fontWeight: FontWeight.w500,
                    fontSize: 16,
                  ),
                ),
                if (_currentProject!.description != null)
                  SelectableText(
                    _currentProject!.description!,
                    style: TextStyle(
                      color: Colors.grey.shade600,
                      fontSize: 12,
                    ),
                  ),
              ],
            ),
          ),
          SelectableText(
            'Excel文件: ${_excelPlans.length}',
            style: TextStyle(
              color: Colors.grey.shade600,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMainContent() {
    return SingleChildScrollView(
      child: Column(
        children: [
          // Excel上传组件
          ExcelUploadWidget(
            project: _currentProject!,
            onUploadSuccess: _onUploadSuccess,
            onUploadError: _onUploadError,
          ),

          // Excel计划列表
          if (_excelPlans.isNotEmpty) _buildExcelPlansList(),
        ],
      ),
    );
  }

  Widget _buildExcelPlansList() {
    return AdaptiveCard(
      margin: const EdgeInsets.all(16),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const Icon(Icons.history, color: Colors.green),
                const SizedBox(width: 8),
                SelectableText(
                  '历史Excel文件',
                  style: Theme.of(context).textTheme.titleLarge,
                ),
                const Spacer(),
                if (_isLoadingPlans)
                  const SizedBox(
                    width: 16,
                    height: 16,
                    child: CircularProgressIndicator(strokeWidth: 2),
                  ),
              ],
            ),
            const SizedBox(height: 16),
            ..._excelPlans.map((plan) => _buildExcelPlanCard(plan)),
          ],
        ),
      ),
    );
  }

  Widget _buildExcelPlanCard(ExcelPlanModel plan) {
    return AdaptiveCard(
      margin: const EdgeInsets.only(bottom: 12),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Row(
          children: [
            Icon(
              Icons.insert_drive_file,
              color: _getStatusColor(plan.status),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    plan.fileName,
                    style: const TextStyle(
                      fontWeight: FontWeight.w500,
                    ),
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                  ),
                  const SizedBox(height: 4),
                  Row(
                    children: [
                      Text(
                        '上传者: ${plan.uploaderName}',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey.shade600,
                        ),
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(width: 16),
                      Text(
                        plan.uploadTime,
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey.shade600,
                        ),
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ],
              ),
            ),
            _buildStatusChip(plan.status),
            const SizedBox(width: 8),
            PopupMenuButton<String>(
              onSelected: (value) => _handlePlanAction(value, plan),
              itemBuilder: (context) => [
                const PopupMenuItem(
                  value: 'view',
                  child: Row(
                    children: [
                      Icon(Icons.visibility),
                      SizedBox(width: 8),
                      Text('查看结果'),
                    ],
                  ),
                ),
                const PopupMenuItem(
                  value: 'download',
                  child: Row(
                    children: [
                      Icon(Icons.download),
                      SizedBox(width: 8),
                      Text('下载文件'),
                    ],
                  ),
                ),
                const PopupMenuItem(
                  value: 'delete',
                  child: Row(
                    children: [
                      Icon(Icons.delete, color: Colors.red),
                      SizedBox(width: 8),
                      Text('删除', style: TextStyle(color: Colors.red)),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildParseResultView() {
    return Column(
      children: [
        // 返回按钮
        Container(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              TextButton.icon(
                onPressed: () => setState(() => _showParseResult = false),
                icon: const Icon(Icons.arrow_back),
                label: const SelectableText('返回'),
              ),
              const Spacer(),
              SelectableText(
                '解析结果',
                style: Theme.of(context).textTheme.titleLarge,
              ),
              const Spacer(),
              const SizedBox(width: 80), // 平衡左侧按钮
            ],
          ),
        ),

        // 解析结果组件
        Expanded(
          child: ExcelParseResultWidget(
            excelPlanId: _currentExcelPlanId!,
            onGenerateTasks: _onGenerateTasks,
          ),
        ),
      ],
    );
  }

  Widget _buildStatusChip(String status) {
    Color color = _getStatusColor(status);
    String text = _getStatusText(status);

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withValues(alpha: 0.3)),
      ),
      child: Text(
        text,
        style: TextStyle(
          color: color,
          fontSize: 12,
          fontWeight: FontWeight.w500,
        ),
        overflow: TextOverflow.ellipsis,
      ),
    );
  }

  Color _getStatusColor(String status) {
    switch (status) {
      case 'UPLOADED':
        return Colors.orange;
      case 'PARSED':
        return Colors.green;
      case 'FAILED':
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  String _getStatusText(String status) {
    switch (status) {
      case 'UPLOADED':
        return '已上传';
      case 'PARSED':
        return '已解析';
      case 'FAILED':
        return '解析失败';
      default:
        return '未知';
    }
  }

  void _handlePlanAction(String action, ExcelPlanModel plan) {
    switch (action) {
      case 'view':
        _viewParseResult(plan.id); // 修复参数类型错误
        break;
      case 'download':
        // 实现下载功能
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: SelectableText('下载功能开发中...')),
        );
        break;
      case 'delete':
        _confirmDeletePlan(plan);
        break;
    }
  }

  void _confirmDeletePlan(ExcelPlanModel plan) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('确认删除'),
        content: SelectableText('确定要删除Excel文件「${plan.fileName}」吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              // 实现删除功能
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: SelectableText('删除功能开发中...'),
                  backgroundColor: Colors.red,
                ),
              );
            },
            child:
                const SelectableText('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }

  void _showProjectSelector() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('选择项目'),
        content: const SizedBox(
          width: 300,
          height: 200,
          child: Center(
            child: SelectableText('项目选择器开发中...'),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
        ],
      ),
    );
  }
}

/// Excel计划数据模型
class ExcelPlanModel {
  final String id;
  final String fileName;
  final String uploaderName;
  final String uploadTime;
  final String status;
  final int fileSize;

  const ExcelPlanModel({
    required this.id,
    required this.fileName,
    required this.uploaderName,
    required this.uploadTime,
    required this.status,
    required this.fileSize,
  });

  /// 创建模拟数据
  static List<ExcelPlanModel> mockList() {
    return [
      const ExcelPlanModel(
        id: '1',
        fileName: '需求文档v1.0.xlsx',
        uploaderName: '张三',
        uploadTime: '2024-01-15 14:30',
        status: 'PARSED',
        fileSize: 1024576,
      ),
      const ExcelPlanModel(
        id: '2',
        fileName: '系统功能列表.xlsx',
        uploaderName: '李四',
        uploadTime: '2024-01-14 10:15',
        status: 'PARSED',
        fileSize: 2048000,
      ),
      const ExcelPlanModel(
        id: '3',
        fileName: '用户故事文档.xlsx',
        uploaderName: '王五',
        uploadTime: '2024-01-13 16:45',
        status: 'UPLOADED',
        fileSize: 512000,
      ),
    ];
  }
}
